﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using UnityScriptEngine;

namespace MBB_Payroll_Terminal
{
    public partial class frmExportDTR : Form
    {
        UnityProcessor proc = new UnityProcessor();
        Threader t = new Threader();
        string prevFile = "";
        string Path = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData) + "\\MBB Terminal Data\\";
        string curFile = "";
        DataTable prvTbl = new DataTable();
        DataTable outTbl = new DataTable();

        public frmExportDTR()
        {
            InitializeComponent();
            InitializeFrameSliderForm();
        }
        private void InitializeForm()
        {
            proc.ProcessCompleted += new ProcessHandler(proc_ProcessCompleted);
            proc.ProcessError += new ProcessHandler(proc_ProcessError);
            btnPreview.Click += new EventHandler(btnPreview_Click);
            btnExport.Click += new EventHandler(btnExport_Click);
            FormatPrevTable();
        }

        bool flushData=false;
        void btnExport_Click(object sender, EventArgs e)
        {
            if (outTbl.Rows.Count > 0)
            {
                if (chkFlush.Checked)
                {
                    flushData = false;
                    DialogResult msg = MessageBox.Show("This operation will flush the DTR data after the export.\r\n" +
                        "Untick the checkbox if you want to preserve the DTR data.\r\n" +
                        "Do you wish to continue?", "Export DTR", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
                    if (msg == System.Windows.Forms.DialogResult.No) return;
                    flushData = true;
                }
                SaveFileDialog dlg = new SaveFileDialog();
                dlg.Filter = "UnityFileFormat|*.uff|All Files|*.*";
                dlg.AddExtension = true;
                dlg.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
                dlg.Title = "Save DTR to File";
                dlg.RestoreDirectory = true;
                dlg.OverwritePrompt = true;
                dlg.FileName = "dtr.uff";

                if (dlg.ShowDialog(this) == System.Windows.Forms.DialogResult.OK)
                {
                    States(false);
                    UnityScript expDtr = new UnityScript("EXPDTR", new object[] { "fEmpNo", "fDate", "fTimeIn", "fTimeOut" });
                    for (int row = 0; row < outTbl.Rows.Count; row++)
                    {
                        UnityElement dat = new UnityElement(expDtr.Desc_Fields());

                        dat.Data_SetField(0, outTbl.Rows[row][0]);
                        if(outTbl.Rows[row][1].ToString().Length > 2)
                            dat.Data_SetField(1, DateTime.Parse(outTbl.Rows[row][1].ToString()).ToString("yyyy-MM-dd"));
                        else
                            dat.Data_SetField(1, "");
                        if (outTbl.Rows[row][2].ToString().Length > 2)
                            dat.Data_SetField(2, DateTime.Parse(outTbl.Rows[row][2].ToString()).ToString("yyyy-MM-dd HH:mm:ss"));
                        else
                            dat.Data_SetField(2, "");
                        if (outTbl.Rows[row][3].ToString().Length > 2)
                            dat.Data_SetField(3, DateTime.Parse(outTbl.Rows[row][3].ToString()).ToString("yyyy-MM-dd HH:mm:ss"));
                        else
                            dat.Data_SetField(3, "");
                        expDtr.Data_AddNew(dat);
                    }
                    curFile = dlg.FileName;
                    expDtr.Desc_FileTitle = "MBB DTR EXPORT FILE";
                    expDtr.Desc_MetaData = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                    expDtr.Script_Add(Script.LFFPU_WRITE, curFile, "elayorbulc");

                    proc.Run(expDtr);
                }
            }
            else
            {
                MessageBox.Show("DTR Preview is empty!", "Export DTR File", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        void btnPreview_Click(object sender, EventArgs e)
        {
             

             UnityScript getPrev = new UnityScript("GETPREV", 5);
             getPrev.Script_Add(Script.LFFPU_READ, Path + "dtr.uff", "elayorbulc");
             proc.Run(getPrev);
            /* Obsolete
            if (!System.IO.Directory.Exists(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData) + "\\MBB Terminal Data\\"))
                    System.IO.Directory.CreateDirectory(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData) + "\\MBB Terminal Data\\");
             OpenFileDialog dlg = new OpenFileDialog();
            dlg.Filter = "Unity File Format|*.uff|All Files|*.*";
            dlg.CheckFileExists = true;
            dlg.InitialDirectory = Path;
            dlg.Title = "Preview DTR";
            dlg.RestoreDirectory = true;
            if (dlg.ShowDialog(this) == System.Windows.Forms.DialogResult.OK)
            {
                prevFile = dlg.FileName;
                States(false);
                UnityScript getPrev = new UnityScript("GETPREV", 5);
                getPrev.Script_Add(Script.LFFPU_READ, prevFile, "elayorbulc");
                proc.Run(getPrev);
            }
            */
        }
        void States(bool state)
        {
            grpFile.Enabled = state;
            grpRange.Enabled = state;
            grdLst.Enabled = state;
        }
        void FormatPrevTable()
        {
            prvTbl.Columns.Add("fEmpNo");
            prvTbl.Columns.Add("fDate");
            prvTbl.Columns.Add("fTimeIn");
            prvTbl.Columns.Add("fTimeOUt");

            prvTbl.Columns[1].DataType = typeof(DateTime);

            outTbl.Columns.Add("fEmpNo");
            outTbl.Columns.Add("fDate");
            outTbl.Columns.Add("fTimeIn");
            outTbl.Columns.Add("fTimeOUt");
        }
        void proc_ProcessError(string id, string desc)
        {
            t.SafeCall(this, delegate
            {
                MessageBox.Show(desc, "Export DTR File", MessageBoxButtons.OK, MessageBoxIcon.Error);
            });
        }

        void proc_ProcessCompleted(string id, string desc)
        {
            t.SafeCall(this, delegate
            {
                switch (id)
                {
                    case "GETPREV":
                        UnityScript getPrev;
                        proc.Data_Fetch(out getPrev);
                        DataTable tmp = getPrev.ToDataTable();
                        prvTbl.Clear();
                        for (int row = 0; row < tmp.Rows.Count; row++)
                        {
                            DataRow dr = prvTbl.NewRow();
                            dr[0] = tmp.Rows[row][0];
                            dr[1] = DateTime.Parse(tmp.Rows[row][1].ToString());
                            dr[2] = tmp.Rows[row][2];
                            dr[3] = tmp.Rows[row][3];

                            prvTbl.Rows.Add(dr);
                        }

                        DataRow[] rows;
                        if (chkAll.Checked)
                            rows = prvTbl.Select();
                        else
                            rows = prvTbl.Select("fDate >= #" + dateFrom.Value.ToShortDateString() + "# AND fDate <= #" + dateTo.Value.ToShortDateString() + "#");

                        outTbl.Clear();
                        for (int row = 0; row < rows.Length; row++)
                        {
                            outTbl.ImportRow(rows[row]);
                        }
                        grdLst.DataSource = outTbl;

                        grdLst.Columns[0].HeaderText = "Employee No.";
                        grdLst.Columns[1].HeaderText = "Date";
                        grdLst.Columns[2].HeaderText = "Time In";
                        grdLst.Columns[3].HeaderText = "Time Out";
                        States(true);
                        break;
                    case "EXPDTR":
                        if (flushData)
                        {
                            flushData = false;
                            //Deleting the file is a mess, rename before deleting.
                            System.IO.File.Copy(string.Format("{0}dtr.uff", Path), string.Format("{0}dtr_{1}.uff", Path, DateTime.Now.ToString("yyyy_MM_dd_HH_mm_ss")));
                            System.IO.File.Delete(Path + "dtr.uff");

                            this.Close();
                            pnlForm.Dispose();
                        }
                        States(true);
                        break;
                }
            });
        }

    }
}
